<template>
  <div class="app-container">
    <ECard
      rightTitle="部门"
      :ilabel="ilabel"
      leftTitle="机构"
      @selectValue="selectValue"
    >
      <template #left>
        <el-button
          type="primary"
          @click="clickNew"
          size="medium"
          :disabled="clickId == ''"
          >新增机构</el-button
        >
        <div class="title">机构列表</div>
        <div class="caidan">
          <div>
            <el-tree
              :data="data"
              node-key="id"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
              :props="defaultProps"
              default-expand-all
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i
                  class="el-icon-office-building"
                  style="margin-right: 10px"
                ></i>
                <span>{{ node.label }}</span>
                <el-dropdown trigger="click" v-if="!topLevel.includes(data.id)">
                  <span class="el-dropdown-link"> ... </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="append(data)"
                      >修改机构</el-dropdown-item
                    >
                    <el-dropdown-item @click.native="remove(node, data)"
                      >删除机构</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </el-tree>
          </div>
        </div>
      </template>
      <template #right>
        <div>
          <EtopSearch
            :options="options"
            @getData="searchFn"
            @resettingFn="resettingFn"
          />
          <el-button
            type="primary"
            @click="newDepartment"
            size="medium"
            :disabled="!clickId"
            >新增部门</el-button
          >
          <el-button
            @click="delBatch()"
            size="medium"
            :disabled="!multipleSelection.length"
            >批量删除</el-button
          >
          <ETable
            ref="ETable"
            style="margin-top: 20px"
            checked
            :height="360"
            :titleObj="titleObj"
            @sortFun="sortFun"
            operateWidth="120"
            :reqObj="setOf"
            :reqFn="getSysOrgDepart"
            @batch="multipleSelection = $event"
          >
            <template v-slot="{ scope }">
              <el-button @click="modifyFn(scope)" type="text" size="small"
                >修改</el-button
              >
              <el-divider direction="vertical"></el-divider>
              <el-button @click="deleteFn(scope)" type="text" size="small"
                >删除</el-button
              >
            </template>
          </ETable>
        </div>
      </template>
    </ECard>
    <!-- 左侧新增/修改机构dialog -->
    <Edialog
      :outershow="institutionShow"
      @saveFn="newInstitutions"
      :title="newInstitutionsTitle"
      saveClick
      @close="newInstitutionsClose"
    >
      <div style="padding: 0 20px">
        <el-form
          ref="form"
          :model="form"
          label-width="100px"
          :rules="newInstitutionsRules"
        >
          <el-form-item label="机构编码" class="line" prop="institutional">
            <el-row style="width: 100%">
              <el-col :span="newInstitutionsTitle == '新增机构' ? 4 : 24"
                ><el-input
                  v-model="clickCode"
                  disabled
                  v-if="clickRoot != ''"
                  :style="{ width: `100%` }"
                ></el-input
              ></el-col>
              <el-col :span="20"
                ><el-input
                  :style="{ width: `100%` }"
                  v-model="form.institutional"
                  v-if="newInstitutionsTitle == '新增机构'"
                  placeholder="请输入4位机构编码"
                ></el-input
              ></el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="机构简称" prop="simple">
            <el-input
              v-model="form.simple"
              placeholder="请输入机构简称（1-40）"
            ></el-input>
          </el-form-item>
          <el-form-item label="代码全称" prop="fullName">
            <el-input
              v-model="form.fullName"
              placeholder="请输入代码全称（1-100）"
            ></el-input>
          </el-form-item>
          <el-form-item label="机构描述">
            <el-input
              v-model="form.describe"
              placeholder="请输入机构描述（0-200）"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="上级机构"
            v-if="newInstitutionsTitle == '新增机构'"
          >
            <el-input v-model="form.superior" disabled></el-input>
          </el-form-item>
        </el-form>
      </div>
    </Edialog>
    <!-- 右侧新增/修改部门dialog -->
    <Edialog
      :outershow="departmentShow"
      :title="departmentTitle"
      saveClick
      @close="departmentClose"
      @saveFn="newSaveFn"
    >
      <div style="padding: 0 20px">
        <el-form
          ref="form1"
          :model="form1"
          label-width="100px"
          :rules="departmentRules"
        >
          <el-form-item label="部门简称" prop="simple">
            <el-input
              v-model="form1.simple"
              placeholder="请输入部门简称（1-40）"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门全称" prop="fullName">
            <el-input
              v-model="form1.fullName"
              placeholder="请输入部门全称（1-100）"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门描述">
            <el-input
              v-model="form1.describe"
              placeholder="请输入部门描述（1-200）"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属机构">
            <el-input
              v-model="form1.superior"
              disabled
              :placeholder="clickRoot"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </Edialog>
  </div>
</template>

<script>
let id = 1000;
import ECard from "@/components/ECard";
import ETable from "@/components/ETable";
import Edialog from "@/components/Edialog";
import EtopSearch from "@/components/EtopSearch";
import {
  getCurrTreeAll,
  getSysOrgId,
  putSysOrg,
  deleteSysOrg,
  postSysOrg,
  getSysOrgDepart,
  putSysOrgDepart,
  deleteSysOrgDepart,
  postSysOrgDepart,
} from "@/api/management/departments";
import { fd } from "@/utils";
export default {
  name: "departments",
  components: {
    ECard,
    ETable,
    Edialog,
    EtopSearch,
  },
  data() {
    return {
      // 校验规则
      newInstitutionsRules: {
        institutional: [
          { required: true, message: "请输入4位机构编码", trigger: "blur" },
          { min: 4, max: 4, message: "请输入4位", trigger: "blur" },
        ],
        simple: [
          {
            required: true,
            message: "请输入机构简称（1-40）",
            trigger: "blur",
          },
          { min: 1, max: 40, message: "请输入1-40位", trigger: "blur" },
        ],
        fullName: [
          {
            required: true,
            message: "请输入代码全称（1-100）",
            trigger: "blur",
          },
          { min: 1, max: 100, message: "请输入1-100位", trigger: "blur" },
        ],
      },
      departmentRules: {
        simple: [
          {
            required: true,
            message: "请输入部门简称（1-40）",
            trigger: "blur",
          },
          { min: 1, max: 40, message: "请输入1-40位", trigger: "blur" },
        ],
        fullName: [
          {
            required: true,
            message: "请输入部门全称（1-100）",
            trigger: "blur",
          },
          { min: 1, max: 100, message: "请输入1-100位", trigger: "blur" },
        ],
      },
      data: [],
      setOf: {
        departName: "",
        orgId: "",
        sortStr: "",
      },
      titleObj: [
        {
          prop: "DEPART_NAME",
          label: "部门简称",
          width: "240",
          sortable: "custom",
        },
        {
          prop: "DEPART_FULL_NAME",
          label: "部门全称",
          width: "280",
          sortable: "custom",
        },
        { prop: "DEPART_DESC", label: "部门描述", minWidth: "90" },
      ],
      defaultProps: {
        children: "children",
        label: "name",
      },
      value: "",
      institutionShow: false,
      departmentShow: false,
      form: {
        simple: "",
        fullName: "",
        describe: "",
        superior: "",
        institutional: "",
      },
      form1: {
        simple: "",
        fullName: "",
        describe: "",
        superior: "",
      },
      clickRoot: "",
      clickId: "",
      clickCode: "",
      clickPid: "",
      departmentTitle: "",
      modifyId: "",
      multipleSelection: [],
      newInstitutionsTitle: "",
      ilabel: "",
      // 顶级机构不允许删除和修改
      topLevel: [],
      options: [
        {
          type: "input",
          name: "部门简称：",
          key: "departName",
          value: "",
        },
      ],
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getSysOrgDepart,
    async getData() {
      let res = await getCurrTreeAll();
      this.data = this.arrayToTree(res.data.bdata, 4);
      this.topLevel = this.data.map((item) => {
        return item.id;
      });
    },
    // 删除元素方法
    async remove(node, data) {
      let t = await this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (t) {
        let res = await deleteSysOrg(data.id);
        if (res.data.bcode == 0) {
          this.$message.success(`${res.data.bmsg}`);
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex((d) => d.id === data.id);
          children.splice(index, 1);
        }
      }
    },
    async handleNodeClick(data) {
      console.log("行点击", data);
      this.ilabel = data.name;
      this.clickId = data.id;
      this.setOf.orgId = data.id;
      this.clickRoot = data.name;
      this.clickCode = data.ab.code;
      this.clickPid = data.pid;
      this.form.superior = data.name;
      this.form1.superior = data.name;
      this.pageFun();
    },
    // 表格排序
    async sortFun(str) {
      this.setOf.sortStr = str;
      this.$refs.ETable.getData();
    },
    // 下拉框选择的值
    selectValue(val) {
      this.value = val;
    },
    modifyFn(row) {
      console.log("右侧修改部门", row);
      this.form1.simple = row.DEPART_NAME;
      this.form1.fullName = row.DEPART_FULL_NAME;
      this.form1.describe = row.DEPART_DESC;
      this.departmentTitle = "修改部门";
      this.departmentShow = true;
      this.modifyId = row.ID;
    },
    async deleteFn(row) {
      let t = await this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (t) {
        let res = await deleteSysOrgDepart(row.ID);
        console.log(res);
        if (res.code == 0 && res.data.bcode == 0) {
          this.$message.success(`${res.data.bmsg}`);
          // 页数大于一页并且当前页只有一条数据，删除后页数-1
          if (
            this.$refs.ETable.pageInfo.total %
              this.$refs.ETable.pageInfo.size ===
              1 &&
            this.$refs.ETable.pageInfo.page > 1
          ) {
            this.$refs.ETable.pageInfo.page -= 1;
          }
          this.$message.success(res.data.bmsg);
          this.$refs.ETable.getData();
        }
      }
    },
    arrayToTree(arr) {
      let list = [];
      // 找一级
      arr.forEach((v) => {
        if (v.id == v.pid) {
          list.push(v);
        } else {
          let one = arr.filter((item) => {
            if (v.pid == item.id) {
              return item;
            }
          });
          if (one.length == 0) {
            list.push(v);
          }
        }
      });
      // 找子级
      list.forEach((item) => {
        let children = this.toTree(arr, item.id);
        item.children = children;
      });
      return list;
    },
    toTree(arr, pid) {
      // 准备一个保存找到节点的数组
      const listArr = [];
      // 遍历找节点
      arr.forEach((v) => {
        if (v.id == v.pid) {
        } else if (v.pid === pid) {
          // 找到加到数组里
          listArr.push(v);
          // 我1级的每个元素还要去找它对应的二级
          // 刚好arrayToTree这个函数就是用来找节点的
          // 只不过此时我要找的pid是我当前一级的id
          const children = this.toTree(arr, v.id);
          // 把找到的子节点挂载到身上
          if (children.length) v.children = children;
        }
      });
      // 遍历完了代表找完了，return这个结果
      return listArr;
    },
    async newInstitutions() {
      if (this.newInstitutionsTitle != "修改机构") {
        if (this.form.institutional.trim() == "") {
          this.form.institutional = "";
          return this.$message.error(`机构编码不允许为空`);
        }
      }
      if (this.form.simple.trim() == "") {
        this.form.simple = "";
        return this.$message.error(`机构简称不允许为空`);
      } else if (this.form.fullName.trim() == "") {
        this.form.fullName = "";
        return this.$message.error(`代码全称不允许为空`);
      }
      // 修改机构不需要校验
      if (this.newInstitutionsTitle == "修改机构") {
        this.newInstitutionsRules.institutional = [];
      } else {
        this.newInstitutionsRules.institutional = [
          { required: true, message: "请输入4位机构编码", trigger: "blur" },
          { min: 4, max: 4, message: "请输入4位", trigger: "blur" },
        ];
      }
      if (this.form.describe.trim().length > 200) {
        return this.$message.error(`长度应在0-200之间`);
      }
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.newInstitutionsTitle == "新增机构") {
            res = await putSysOrg(
              fd({
                orgCode: this.clickCode + this.form.institutional,
                orgFullName: this.form.fullName,
                orgName: this.form.simple,
                pid: this.clickId,
                orgDesc: this.form.describe,
              })
            );
          } else {
            res = await postSysOrg(
              fd({
                id: this.clickId,
                orgCode: this.clickCode,
                pid: this.clickPid,
                orgFullName: this.form.fullName,
                orgName: this.form.simple,
                orgDesc: this.form.describe,
              })
            );
          }
          if (res.data.bcode == 0) {
            this.$message.success(`${res.data.bmsg}`);
            this.institutionShow = false;
            this.form = {
              simple: "",
              fullName: "",
              describe: "",
              superior: "",
              institutional: "",
            };
            this.getData();
          }
        }
      });
    },
    newInstitutionsClose() {
      this.$refs.form.clearValidate();
      this.institutionShow = false;
      this.form = {
        simple: "",
        fullName: "",
        describe: "",
        superior: "",
        institutional: "",
      };
    },
    // 新增部门按钮事件
    newDepartment() {
      this.departmentShow = true;
      this.departmentTitle = "新增部门";
    },
    // 查询
    async searchDep() {
      if (!this.clickId) return this.$message.error("请先点击机构！");
      this.pageFun();
    },
    searchFn(val) {
      if (!this.clickId) return this.$message.error("请先点击机构！");
      // 保存传递出来的搜索数据，用于表格请求
      this.setOf.departName = val.departName;
      this.pageFun();
    },
    // 重置
    resettingFn() {
      if (!this.clickId) return;
      // 重置搜索数据以及搜索框的options数据
      this.options.forEach((element) => (element.value = ""));
      this.setOf.departName = "";
    },
    async newSaveFn() {
      this.$refs.form1.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.departmentTitle == "新增部门") {
            res = await putSysOrgDepart(
              fd({
                departFullName: this.form1.fullName,
                departName: this.form1.simple,
                departDesc: this.form1.describe,
                orgId: this.clickId,
              })
            );
          } else {
            res = await postSysOrgDepart(
              fd({
                departFullName: this.form1.fullName,
                departName: this.form1.simple,
                departDesc: this.form1.describe,
                orgId: this.clickId,
                id: this.modifyId,
              })
            );
          }
          if (res.code == 0 && res.data.bcode == 0) {
            this.$message.success(`${res.data.bmsg}`);
            this.pageFun();
            this.departmentShow = false;
          }
        }
      });
    },
    departmentClose() {
      this.departmentShow = false;
      this.$refs.form1.clearValidate();
      this.form1 = {
        simple: "",
        fullName: "",
        describe: "",
        superior: "",
      };
    },
    async delBatch() {
      let t = await this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      if (t) {
        let arr = this.multipleSelection.map((item) => item.ID);
        let res = await deleteSysOrgDepart(arr.join());
        if (res.data.bcode == 0) {
          this.$message.success(`${res.data.bmsg}`);
          this.pageFun();
        }
      }
    },
    async append(scope) {
      console.log("修改机构", scope);
      this.newInstitutionsTitle = "修改机构";
      let res = await getSysOrgId(scope.id);
      this.form.simple = res.data.bdata.orgName;
      this.form.fullName = res.data.bdata.orgFullName;
      this.form.describe = res.data.bdata.orgDesc;
      this.institutionShow = true;
    },
    // 新增机构
    clickNew() {
      this.form.superior = this.clickRoot;
      this.newInstitutionsTitle = "新增机构";
      this.institutionShow = true;
    },
    async pageFun() {
      this.$refs.ETable.pageInfo.page = 1;
      this.$refs.ETable.getData();
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep {
  .el-card__body {
    position: relative !important;
  }
}
.title {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background-color: #66b1ff;
  color: #fff;
  margin-top: 20px;
  font-size: 14px;
}
.caidan {
  width: 100%;
  height: calc(100vh - 354px);
  border: 1px solid #ccc;
  overflow: auto;
  &::-webkit-scrollbar {
    display: none;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    padding-right: 8px;
  }
  .el-dropdown {
    position: absolute;
    background-color: #fff;
    right: 0px;
    width: 20px;
  }

  .el-tree-node:focus > .el-tree-node__content .el-dropdown {
    background-color: #f5f7fa;
  }
  .el-tree-node__content:hover .el-dropdown {
    background-color: #f5f7fa;
  }

  .el-dropdown .el-button {
    width: 10px;
    height: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.serach {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .el-input {
    width: 250px;
    margin: 0 10px;
  }
}
.line {
  ::v-deep .el-form-item__content {
    display: flex;
    .is-disabled {
      width: 80px;
      width: inherit;
      margin-right: 10px;
    }
  }
}
</style>
